package com.sz.zhiling.consumer;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 这是消息队列的消费者
 */
public class MQConsumer {
    public static void main(String[] args) {
        //创建连接工厂
        ConnectionFactory factory=new ConnectionFactory();
        //配置密码
        factory.setPassword("jontang");
        //配置用户名
        factory.setUsername("jonTang");
        //配置虚拟主机
        factory.setVirtualHost("/jontang");
        //配置端口
        factory.setPort(5672);
        //配置主机
        factory.setHost("10.1.12.117");
        //创建连接对象
        Connection connection=null;
        Channel channel=null;
        try {
           connection = factory.newConnection();
           channel=connection.createChannel();
           channel.queueDeclare("work_queues",true,false,false,null);
            Consumer consumer=new DefaultConsumer(channel){
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    super.handleDelivery(consumerTag, envelope, properties, body);
                    System.out.println("body:"+new String(body));
                }
            };

            channel.basicConsume("work_queues",true,consumer);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
    }
}
